import {ScriptLibraryManager} from "../managers/ScriptLibraryManager";
import {JsLibLoader} from "./ThirdLibraryLoader";
import jQuery from 'jquery';

class ModuleLibLoader {
    constructor() {
    }

    load(bundle) {
        let def = jQuery.Deferred();
        if (bundle.prototype.__dependLibs &&
            Array.prototype.isArray(bundle.prototype.__dependLibs)) {
            const dependLibs = bundle.prototype.__dependLibs;
            let scripts = [];
            //检查需要加载的第三方库
            dependLibs.forEach(item => {
                if (ScriptLibraryManager.getInstance().exists(item)) {
                    let config = ScriptLibraryManager.getInstance().get(item);
                    //如果未载过
                    if (config.loaded === false) {
                        scripts.push(config);
                    }
                }
            });
            if (scripts.length === 0) {
                //没有需要额外加载的类库
                def.resolve();
            } else {
                let loadLibs = [];
                scripts.forEach(lib => {
                    JsLibLoader.findDependScript(lib, loadLibs);
                });
                let loader = JsLibLoader.getInstance().create();
                loader.load(loadLibs).done(() => {
                    //类库加载完成
                    loadLibs.forEach(item => {
                        item.loaded = true;
                    });
                    def.resolve();
                }).fail(() => {
                    console.error('Load bundle depend library error');
                    def.reject();
                });
            }
        } else {
            def.resolve();
        }
        return def.promise();
    }
}

export const ModuleLoader = (function () {
    let instance;
    return {
        name: "ModuleLoader",
        getInstance: () => {
            if (instance === undefined) {
                instance = new ModuleLibLoader();
            }
            return instance
        }
    }
})();